package com.qingcheng.controller;

import com.qingcheng.entity.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @author lin.jia
 */
@ControllerAdvice
public class ResponseBodyHandler implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Class returnType = Objects.requireNonNull(methodParameter.getMethod()).getReturnType();
        if (o instanceof Result) {
            return o;
        }
        if (returnType.equals(ResponseEntity.class)) {
            return o;
        }
        Result responseVo = new Result();
        responseVo.setData(o);
        return responseVo;
    }
}
